package com.yunlongn.common.json.jackson.deserializer;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.yunlongn.common.json.jackson.factory.AbstractJsonDeserializer;
import com.yunlongn.common.json.util.DateFormatException;
import com.yunlongn.common.json.util.DateFormatUtils;
import com.yunlongn.common.json.util.StringUtils;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 日期反序列化
 * @author Yun
 * @since 20210902
 */
public class DateDeserializer extends AbstractJsonDeserializer<Date> {

    
    
    @Override
    public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        String datetime = jsonParser.getText();
        if (StringUtils.isNumber(datetime)) {
            if (datetime.length() == 10) {
                return new Date(Long.parseLong(datetime) * 1000);
            } else {
                return new Date(Long.parseLong(datetime));
            }
        }
        
        SimpleDateFormat sfg = DateFormatUtils.chooseSimpleDateFormat(datetime);
        try {
            return sfg.parse(datetime);
        } catch (ParseException e) {
            throw new DateFormatException(datetime);
        }
    }

}
